const express = require('express');
const router = express.Router();
const menuService = require('../services/menuService');

/**
 * 获取所有菜品列表
 * GET /api/menu
 */
router.get('/', async (req, res) => {
  try {
    const { category, weatherCondition, search, sortBy, includeInactive } = req.query;

    const filters = {
      category,
      weatherCondition,
      search,
      sortBy,
      includeInactive: includeInactive === 'true'
    };

    const dishes = await menuService.getAllDishes(filters);

    res.json({
      success: true,
      data: dishes,
      total: dishes.length
    });
  } catch (error) {
    console.error('获取菜品列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取菜品列表失败，请稍后重试'
    });
  }
});

/**
 * 获取菜品分类列表
 * GET /api/menu/categories
 */
router.get('/categories', async (req, res) => {
  try {
    const categories = await menuService.getCategories();

    res.json({
      success: true,
      data: categories
    });
  } catch (error) {
    console.error('获取分类列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类列表失败'
    });
  }
});

/**
 * 根据天气获取推荐菜品
 * GET /api/menu/recommended
 */
router.get('/recommended', async (req, res) => {
  try {
    const { weatherCondition, temperature } = req.query;

    if (!weatherCondition || !temperature) {
      return res.status(400).json({
        success: false,
        message: '缺少天气参数'
      });
    }

    const recommendedDishes = await menuService.getRecommendedDishes(
      weatherCondition,
      parseFloat(temperature)
    );

    res.json({
      success: true,
      data: recommendedDishes
    });
  } catch (error) {
    console.error('获取推荐菜品失败:', error);
    res.status(500).json({
      success: false,
      message: '获取推荐菜品失败'
    });
  }
});

/**
 * 搜索菜品
 * GET /api/menu/search
 */
router.get('/search', async (req, res) => {
  try {
    const { keyword } = req.query;

    if (!keyword) {
      return res.status(400).json({
        success: false,
        message: '搜索关键词不能为空'
      });
    }

    const searchResults = await menuService.searchDishes(keyword);

    res.json({
      success: true,
      data: searchResults,
      total: searchResults.length
    });
  } catch (error) {
    console.error('搜索菜品失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索菜品失败'
    });
  }
});

/**
 * 批量获取菜品（用于购物车）
 * POST /api/menu/batch
 */
router.post('/batch', async (req, res) => {
  try {
    const { dishIds } = req.body;

    if (!dishIds || dishIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '菜品ID列表不能为空'
      });
    }

    const dishes = await menuService.getDishesByIds(dishIds);

    res.json({
      success: true,
      data: dishes
    });
  } catch (error) {
    console.error('批量获取菜品失败:', error);
    res.status(500).json({
      success: false,
      message: '批量获取菜品失败'
    });
  }
});

/**
 * 上传菜品图片
 * POST /api/menu/upload
 */
router.post('/upload', (req, res) => {
  const upload = req.app.get('upload');
  
  upload.single('image')(req, res, (err) => {
    if (err) {
      console.error('图片上传失败:', err);
      return res.status(400).json({
        success: false,
        message: err.message || '图片上传失败'
      });
    }

    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未上传文件'
      });
    }

    const imageUrl = `/uploads/${req.file.filename}`;

    res.json({
      success: true,
      message: '图片上传成功',
      data: {
        url: imageUrl,
        filename: req.file.filename,
        size: req.file.size,
        mimetype: req.file.mimetype
      }
    });
  });
});

/**
 * 更新菜品上架状态
 * PATCH /api/menu/:id/status
 */
router.patch('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    // 验证参数
    if (typeof status !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: '状态值必须为布尔类型'
      });
    }

    // 使用专用的toggleDishStatus方法确保状态正确更新
    const updatedDish = await menuService.toggleDishStatus(id, status);

    // 实时推送更新到点菜窗口
    const io = req.app.get('io');
    if (io) {
      io.to('customer').emit('menu-updated', {
        action: 'status-change',
        dish: updatedDish
      });
    }

    // 记录日志
    console.log(`✓ 菜品状态更新成功: ID=${id}, 新状态=${status ? '已上架' : '已下架'}`);

    res.json({
      success: true,
      message: status ? '菜品已上架' : '菜品已下架',
      data: updatedDish
    });
  } catch (error) {
    console.error('更新菜品状态失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '更新菜品状态失败'
    });
  }
});

/**
 * 获取菜品详情
 * GET /api/menu/:dishId
 */
router.get('/:dishId', async (req, res) => {
  try {
    const { dishId } = req.params;

    const dish = await menuService.getDishById(dishId);

    res.json({
      success: true,
      data: dish
    });
  } catch (error) {
    console.error('获取菜品详情失败:', error);
    res.status(404).json({
      success: false,
      message: error.message || '菜品不存在'
    });
  }
});

/**
 * 创建新菜品（商户端）
 * POST /api/menu
 */
router.post('/', async (req, res) => {
  try {
    const { name, price, description, imageUrl, category, weatherCondition, recipe } = req.body;

    // 增强数据验证
    if (!name || !name.trim()) {
      console.error('创建菜品失败: 菜品名称不能为空');
      return res.status(400).json({
        success: false,
        message: '菜品名称不能为空'
      });
    }

    if (!price || parseFloat(price) <= 0) {
      console.error('创建菜品失败: 价格必须大于0');
      return res.status(400).json({
        success: false,
        message: '价格必须大于0'
      });
    }

    if (!category || !category.trim()) {
      console.error('创建菜品失败: 菜品分类不能为空');
      return res.status(400).json({
        success: false,
        message: '菜品分类不能为空'
      });
    }

    if (!description || !description.trim()) {
      console.error('创建菜品失败: 菜品描述不能为空');
      return res.status(400).json({
        success: false,
        message: '菜品描述不能为空'
      });
    }

    // 构建菜品数据
    const dishData = {
      name: name.trim(),
      price: parseFloat(price),
      description: description.trim(),
      imageUrl: imageUrl || 'https://haisnap.tos-cn-beijing.volces.com/image/a8b861cb-e2ae-4085-b201-4fb302b0faf6_1760936728562.jpg',
      category: category.trim(),
      weatherCondition: weatherCondition || 'normal',
      recipe: recipe ? recipe.trim() : '暂无制作步骤'
    };

    console.log('开始创建菜品，数据:', JSON.stringify(dishData, null, 2));

    // 调用Service层创建菜品
    const newDish = await menuService.createDish(dishData);

    console.log(`✓ 菜品创建成功: ID=${newDish.id}, 名称=${newDish.name}`);

    // 实时推送新菜品到点菜窗口
    const io = req.app.get('io');
    if (io) {
      io.to('customer').emit('menu-updated', {
        action: 'add',
        dish: newDish
      });
    }

    res.status(201).json({
      success: true,
      message: '菜品创建成功',
      data: newDish
    });
  } catch (error) {
    console.error('创建菜品失败:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({
      success: false,
      message: error.message || '创建菜品失败，请稍后重试'
    });
  }
});

/**
 * 更新菜品信息（商户端）
 * PUT /api/menu/:dishId
 */
router.put('/:dishId', async (req, res) => {
  try {
    const { dishId } = req.params;
    const updateData = req.body;

    if (Object.keys(updateData).length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供更新数据'
      });
    }

    if (updateData.name !== undefined && (!updateData.name || !updateData.name.trim())) {
      return res.status(400).json({
        success: false,
        message: '菜品名称不能为空'
      });
    }

    if (updateData.price !== undefined && parseFloat(updateData.price) <= 0) {
      return res.status(400).json({
        success: false,
        message: '价格必须大于0'
      });
    }

    const updatedDish = await menuService.updateDish(dishId, updateData);

    const io = req.app.get('io');
    if (io) {
      io.to('customer').emit('menu-updated', {
        action: 'update',
        dish: updatedDish
      });
    }

    res.json({
      success: true,
      message: '菜品更新成功',
      data: updatedDish
    });
  } catch (error) {
    console.error('更新菜品失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '更新菜品失败'
    });
  }
});

/**
 * 删除菜品（商户端）
 * DELETE /api/menu/:dishId
 */
router.delete('/:dishId', async (req, res) => {
  try {
    const { dishId } = req.params;

    const deleted = await menuService.deleteDish(dishId);

    if (deleted) {
      const io = req.app.get('io');
      if (io) {
        io.to('customer').emit('menu-updated', {
          action: 'delete',
          dishId: dishId
        });
      }

      res.json({
        success: true,
        message: '菜品删除成功'
      });
    } else {
      res.status(404).json({
        success: false,
        message: '菜品不存在'
      });
    }
  } catch (error) {
    console.error('删除菜品失败:', error);
    res.status(500).json({
      success: false,
      message: '删除菜品失败'
    });
  }
});

module.exports = router;